package com.shuda.business.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuda.business.user.entity.PermissionEntity;
import com.shuda.business.user.mapper.PermissionMapper;
import com.shuda.business.user.service.PermissionService;
import com.shuda.common.dto.PermissionDTO;
import com.shuda.common.exception.BusinessException;
import com.shuda.common.utils.BeanCopyUtils;
import com.shuda.common.vo.PermissionVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 权限服务实现类
 * @author ink
 * @Description: 权限业务逻辑实现
 * @date 2024-10-10 14:30:00
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, PermissionEntity> implements PermissionService {

    @Override
    public IPage<PermissionEntity> getPermissionList(Integer pageNum, Integer pageSize, String permissionName, String permissionCode, Integer status) {
        QueryWrapper<PermissionEntity> queryWrapper = new QueryWrapper<>();
        
        if (permissionName != null && !permissionName.trim().isEmpty()) {
            queryWrapper.like("permission_name", permissionName);
        }
        
        if (permissionCode != null && !permissionCode.trim().isEmpty()) {
            queryWrapper.like("permission_code", permissionCode);
        }
        
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        
        queryWrapper.orderByDesc("create_time");
        
        return this.page(new Page<>(pageNum, pageSize), queryWrapper);
    }

    @Override
    public List<PermissionVO> getPermissionTree() {
        QueryWrapper<PermissionEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1).orderByAsc("sort");
        
        List<PermissionEntity> permissions = this.list(queryWrapper);
        
        return permissions.stream()
                .map(permission -> {
                    PermissionVO vo = new PermissionVO();
                    vo.setId(permission.getId());
                    vo.setPermissionName(permission.getPermissionName());
                    vo.setPermissionCode(permission.getPermissionCode());
                    vo.setParentId(permission.getParentId());
                    vo.setPermissionType(permission.getPermissionType());
                    vo.setSort(permission.getSort());
                    vo.setStatus(permission.getStatus());
                    return vo;
                })
                .collect(Collectors.toList());
    }

    @Override
    public PermissionEntity getPermissionById(Long id) {
        return this.getById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean createPermission(PermissionDTO permissionDTO) {
        // 检查权限编码是否已存在
        QueryWrapper<PermissionEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("permission_code", permissionDTO.getPermissionCode());
        
        if (this.count(queryWrapper) > 0) {
            throw new BusinessException("权限编码已存在");
        }
        
        PermissionEntity permission = new PermissionEntity();
        BeanCopyUtils.copyProperties(permissionDTO, permission);
        
        permission.setStatus(1);
        permission.setDeleted(0);
        permission.setCreateTime(LocalDateTime.now());
        permission.setUpdateTime(LocalDateTime.now());
        
        return this.save(permission);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updatePermission(Long id, PermissionDTO permissionDTO) {
        PermissionEntity permission = this.getById(id);
        if (permission == null) {
            throw new BusinessException("权限不存在");
        }
        
        // 检查权限编码是否已存在（排除自己）
        QueryWrapper<PermissionEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("permission_code", permissionDTO.getPermissionCode())
                   .ne("id", id);
        
        if (this.count(queryWrapper) > 0) {
            throw new BusinessException("权限编码已存在");
        }
        
        BeanCopyUtils.copyProperties(permissionDTO, permission);
        permission.setUpdateTime(LocalDateTime.now());
        
        return this.updateById(permission);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deletePermission(Long id) {
        return this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updatePermissionStatus(Long id, Integer status) {
        PermissionEntity permission = this.getById(id);
        if (permission == null) {
            throw new BusinessException("权限不存在");
        }
        
        permission.setStatus(status);
        permission.setUpdateTime(LocalDateTime.now());
        
        return this.updateById(permission);
    }

    @Override
    public List<PermissionVO> getPermissionOptions() {
        QueryWrapper<PermissionEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1).orderByAsc("sort");
        
        List<PermissionEntity> permissions = this.list(queryWrapper);
        
        return permissions.stream()
                .map(permission -> {
                    PermissionVO vo = new PermissionVO();
                    vo.setId(permission.getId());
                    vo.setPermissionName(permission.getPermissionName());
                    vo.setPermissionCode(permission.getPermissionCode());
                    vo.setPermissionType(permission.getPermissionType());
                    return vo;
                })
                .collect(Collectors.toList());
    }
}